<!--
 * @Author: pmy
 * @Date: 2021-07-29 10:34:06
 * @LastEditTime: 2023-07-31 15:20:48
 * @LastEditors: pmy
 * @Description: 系统菜单
 * @FilePath: \bdcar-net\src\components\views\systemManage\systemMenu.vue
-->
<template>
  <div>
    <div class="tablePage" v-loading="tableLoading">
      <div class="search">
        <div class="add-btn" @click="handleClick({ name: '根节点', id: '-1', type: 0 }, 'add')" v-if="isEditPermission">
          <div class="btn-img"></div>新增
        </div>
        <div class="search-btn" @click="getTableData()">
          <div class="btn-img"></div>查询
        </div>
      </div>
      <div class="base-table">
        <el-table highlight-current-row :data="tableData"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="id" height="100%">
          <el-table-column prop="name" label="名称" align="left" header-align="left"></el-table-column>
          <el-table-column label="类型" align="left" header-align="left">
            <template slot-scope="scope">
              <span v-if="scope.row.type == 1" style="color: deepskyblue;">目录</span>
              <span style="margin-left:2rem;color: darkorange;" v-else-if="scope.row.type == 2">菜单</span>
              <!-- <span style="margin-left:4rem" v-else>按钮</span> -->
            </template>
          </el-table-column>
          <el-table-column prop="url" label="路径" align="left" header-align="left"></el-table-column>
          <el-table-column prop="orderKey" label="序号" align="left" header-align="left"></el-table-column>
          <el-table-column label="操作" align="left" header-align="left">
            <template slot-scope="scope" v-if="isEditPermission">
              <div @click="handleClick(scope.row, 'add')" class="other-btn" v-show="scope.row.type < 2">
                新增
              </div>
              <div @click="handleClick(scope.row, 'edit')" class="edit-btn">
                <div class="btn-img"></div>编辑
              </div>
              <div @click="handleClick(scope.row, 'Delete')" class="delete-btn">
                <div class="btn-img"></div>删除
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog v-dialogDrag :visible="!!showWhich" top="10%" width="30%" :close-on-click-modal="false"
        :before-close="handleCloseEdit">
        <template #title>
          <div class="dialog-title">
            <div class="cicle"></div>
            <span>{{ showWhichType === 1 ? '新增' : '编辑' }}</span>
          </div>
        </template>
        <div class="body" @mousedown.stop v-if="!!showWhich">
          <el-form :inline="true" :rules="SystemMenuRules" ref="systemMenuRef" :model="systemMenuInfo">
            <el-form-item label="上级菜单" v-show="showWhichType === 1">
              <el-input v-model.trim="parentName" disabled></el-input>
            </el-form-item>
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="systemMenuInfo.type">
                <el-radio :label="1">目录</el-radio>
                <el-radio :label="2">菜单</el-radio>
                <!-- <el-radio :label="3">按钮</el-radio> -->
              </el-radio-group>
            </el-form-item>
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model.trim="systemMenuInfo.name"></el-input>
            </el-form-item>
            <el-form-item label="路径" prop="url">
              <el-input v-model.trim="systemMenuInfo.url"></el-input>
            </el-form-item>
            <el-form-item label="排序号" prop="orderKey">
              <el-input v-model.trim="systemMenuInfo.orderKey"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="tool-bar">
          <div class="cancel-btn" @click="handleCloseEdit">关闭</div>
          <div class="submit-btn" @click="handleSystemMenu">确定</div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { service } from "@/services/backServices"
import { TreeCreate } from "@/assets/js/createTree"
export default {
  name: "systemMenu",
  data() {
    return {
      tableLoading: false,
      tableData: [],
      // 显示遮罩层
      showWhich: false,
      // 1则添加 为0则编辑
      showWhichType: '',
      // 记录初始化的数据，在编辑后充值
      row: {},
      systemMenuInfo: {
        // 上级菜单
        parentId: '',
        // 菜单类型
        type: '',
        // 菜单名称
        name: '',
        // 链接地址
        url: '',
        // 排序号
        orderKey: '',
      },
      parentName: '',
      SystemMenuRules: {
        // 菜单类型
        type: [
          { required: true, message: '请选择菜单类型', trigger: 'blur' },
          { required: true, message: '请选择菜单类型', trigger: 'change' },
        ],
        // 备注
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { required: true, message: '请输入菜单名称', trigger: 'change' },
        ],
      },
    };
  },
  mounted() {
    //初始化表格数据
    this.getTableData();
  },
  methods: {
    object2FormData(obj) {
      const formData = new FormData();
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          formData.append(key, obj[key]);
        }
      }
      return formData;
    },
    resetSystemMenuInfo() {
      this.systemMenuInfo = {
        // 上级菜单
        parentId: '',
        // 菜单类型
        type: '',
        // 菜单名称
        name: '',
        // 链接地址
        url: '',
        // 排序号
        orderKey: '',
      };
    },
    setSystemMenuInfo(row) {
      this.systemMenuInfo.parentId = row.parentId;
      this.systemMenuInfo.type = Number(row.type);
      this.systemMenuInfo.name = row.name;
      this.systemMenuInfo.url = row.url;
      this.systemMenuInfo.orderKey = row.orderKey;
      this.systemMenuInfo.id = row.id ?? null;
      this.parentName = row.name;
    },
    // 增删改查
    handleClick(row, obj) {
      switch (obj) {
        case "add":
          this.resetSystemMenuInfo()
          this.parentName = row.name;
          this.showWhichType = 1;
          this.showWhich = true;
          this.systemMenuInfo.parentId = row.id;
          this.systemMenuInfo.type = Number(row.type) + 1;
          break;
        case "edit":
          this.showWhichType = 0;
          this.row = row;
          this.setSystemMenuInfo(row);
          this.showWhich = true;
          break;
        case "Delete":
          this.deleteSystemMenu(row);
          break;
        default:
          break;
      }
    },
    // 关闭
    handleCloseEdit() {
      if (this.showWhichType === 0) {
        this.resetSystemMenuInfo()
        this.row = {}
      }
      this.showWhich = false;
    },
    //获取表格数据
    getTableData() {
      this.tableLoading = true
      service({
        url: "getAllView",
        method: "post"
      }).then((res) => {
        this.tableLoading = false
        if (res.data.code == 200) {
          res.data.data.sort((a, b) => a.orderKey - b.orderKey)
          let tree = new TreeCreate(res.data.data)
          this.tableData = tree.getData().children
        }
      }).catch((err) => {
        this.$notify({
          message: "数据库信息查询失败！",
          type: "error",
          position: "bottom-right",
          duration: 2000,
        });
        this.tableLoading = false
        this.tableData = []
      });
    },
    handleSystemMenu() {
      this.$refs.systemMenuRef.validate((valid) => {
        if (valid) {
          switch (this.showWhichType) {
            case 1:
              this.addSystemMenu();
              break;
            case 0:
              this.updateSystemMenu();
              break;
            default:
              break;
          }
        }
      })
    },
    addSystemMenu() {
      service({
        url: "addView",
        method: "post",
        data: this.object2FormData(this.systemMenuInfo)
      }).then(res => {
        if (res.data.code === 200) {
          this.$notify({
            message: "添加菜单成功！",
            type: "success",
            position: "bottom-right",
            duration: 2000,
          });
          this.getTableData();
          this.showWhich = false;
        }
      })
    },
    async updateSystemMenu() {
      const updateData = await service({
        url: "editView",
        method: "post",
        data: this.object2FormData(this.systemMenuInfo)
      })
      if (updateData.data.code === 200) {
        this.$notify({
          message: "修改菜单成功！",
          type: "success",
          position: "bottom-right",
          duration: 2000,
        });
        this.row = {};
        this.getTableData();
        this.showWhich = false;
        this.resetSystemMenuInfo();
      }
    },
    deleteSystemMenu(row) {
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let params = new FormData()
        params.append('viewId', row.id)
        const { data } = await service({ url: "deleteView", method: "post", data: params })
        if (data.code === 200) {
          this.getTableData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          return
        }
      });
    },
  },
  computed: {
    //获取用户信息
    userData() {
      return this.$store.state.currentUser;
    },
    isEditPermission() {
      return this.userData.roleType == '-1'
    }
  },
}
</script>
<style scoped lang="less"></style>